const express = require('express');
const http = require('http');
const socketIO = require('socket.io');
const path = require('path');

const app = express();
const server = http.createServer(app);
const io = socketIO(server);

// 添加安全头
app.use((req, res, next) => {
    res.setHeader(
        'Content-Security-Policy',
        "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline';"
    );
    next();
});

// 添加静态文件服务
app.use(express.static(path.join(__dirname)));

// 添加根路由处理
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'index.html'));
});

let messages = [];

io.on('connection', (socket) => {
    console.log('A user connected');
    socket.emit('initialMessages', messages);

    socket.on('newMessage', (message) => {
        messages.push(message);
        io.emit('newMessage', message);
    });

    socket.on('disconnect', () => {
        console.log('A user disconnected');
    });
});

// 错误处理中间件
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Something broke!');
});

server.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
    console.log('Current directory:', __dirname);
});
